package com.erp.erp_ui.business.controller;

import com.alibaba.fastjson.JSONObject;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_entitys.business.req.*;
import com.erp.erp_entitys.business.rsp.DetailShippedUnExchangeRsp;
import com.erp.erp_entitys.business.rsp.DetailUnBillExchangeRsq;
import com.erp.erp_entitys.business.rsp.PurchaseStatisticsTwoRes;
import com.erp.erp_entitys.business.rsp.StatisticShippingDetailRsp;
import com.erp.erp_ui.base.Base;
import com.erp.erp_ui.business.req.*;
import com.erp.erp_ui.business.service.CarryDetailService;
import com.erp.erp_ui.business.vo.*;
import com.erp.erp_ui.money.req.OperationReq;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName : CarryDetailController
 * @Description : 出运明细控制层
 * @Author : lst
 * @Date: 2020-06-26 17:11
 */
@Controller
@RequestMapping(value = "carryDetail")
public class CarryDetailController extends Base {

    /**
     * 日志
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CarryDetailController.class);

    /**
     * 出运明细service层
     */
    private final CarryDetailService carryDetailService;

    @Autowired
    public CarryDetailController(CarryDetailService carryDetailService) {
        this.carryDetailService = carryDetailService;
    }


    /**
     * 首页-分页列表查询
     *
     * @param req 查询参数
     * @return 分页信息
     */
    @GetMapping("/getListByPage")
    @ResponseBody
    public R getListByPage(CarryDetailPageListReq req) {
        try {
            LOGGER.info("首页-分页列表查询 req=" + req.toString());
            PageInfo<CarryDetailPageListVo> pageInfo = carryDetailService.getListByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("首页-分页列表查询异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 删除
     *
     * @param req 删除条件
     * @return 删除结果
     */
    @PostMapping("/delete")
    @ResponseBody
    public R delete(@RequestBody OperationReq req) {
        try {
            LOGGER.info("出口业务-出运明细-删除 req=" + req);
            carryDetailService.delete(req);
            return R.build("");
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-删除异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }

    }

    /**
     * 数据操作接口
     *
     * @param req
     * @return
     */
    @PostMapping("/operation")
    @ResponseBody
    public R operation(@RequestBody OperationReq req) {
        try {
            LOGGER.info("出口业务-出运明细-数据操作接口 req=" + req);
            UserEntity user = (UserEntity) this.getBean("user");
            return carryDetailService.operation(req, user);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-数据操作接口异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 数据批量操作接口
     * @param req 操作类型
     * @return 操作结果
     */
    @PostMapping("/batchOperation")
    @ResponseBody
    public R batchOperation(@RequestBody BatchOperationReq req) {
        try {
            LOGGER.info("出口业务-出运明细-数据批量操作 req=" + req);
            return carryDetailService.batchOperation(req);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-数据批量操作异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 导入-获取出运计划主表关联验货信息
     *
     * @param req 查询条件
     * @return 出运计划信息
     */
    @GetMapping("/importCarryPlanByPage")
    @ResponseBody
    public R importCarryPlanByPage(ImportCarryPlanReq req) {
        try {
            LOGGER.info("出口业务-出运明细-导入出运计划信息 req=" + req);
            PageInfo<ImportCarryPlanVo> pageInfo = carryDetailService.getShipmentPlanInfo(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-导入出运计划信息异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 导入-获取出运计划子表关联验货信息
     *
     * @param id 出运计划主键
     * @return 出运计划关联验货产品信息
     */
    @GetMapping("/import/getCarryPlanProduct")
    @ResponseBody
    public R importCarryPlanProduct(Integer id) {
        try {
            LOGGER.info("出口业务-出运明细-导入-获取出运计划关联验货产品信息：id=" + id);
            List<ImportCarryPlanProductVo> products = carryDetailService.importCarryPlanProduct(id);
            return R.build(products);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-导入-获取出运计划关联验货产品信息异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 导入-出运计划主表关联调拨信息
     *
     * @param req 查询条件
     * @return 出运计划主表关联调拨信息
     */
    @GetMapping("/import/carryPlanAssociateTransferByPage")
    @ResponseBody
    public R importCarryPlanAssociateTransferByPage(ImportCarryPlanInfoReq req) {
        try {
            LOGGER.info("出口业务-出运明细-出运计划主表关联调拨信息 req=" + req);
            PageInfo<ImportCarryPlanVo> pageInfo = carryDetailService.importCarryPlanAssociateTransferByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-出运计划主表关联调拨信息异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 导入-获取出运计划子表关联调拨信息
     *
     * @param id 出运计划主键
     * @return 出运计划关联调拨产品信息
     */
    @GetMapping("/import/getCarryPlanProductAssociateTransfer")
    @ResponseBody
    public R importCarryPlanProductAssociateTransfer(Integer id) {
        try {
            LOGGER.info("出口业务-出运明细-导入-获取出运计划子表关联调拨信息：id=" + id);
            List<ImportCarryPlanProductVo> products = carryDetailService.importCarryPlanProductAssociateTransfer(id);
            return R.build(products);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-导入-获取出运计划子表关联调拨信息异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 新增、修改
     *
     * @param req 新增、修改入参
     * @return 新增、修改结果
     */
    @PostMapping("/add")
    @ResponseBody
    public R add(@Validated @RequestBody AddCarryDetailReq req) {
        try {
            LOGGER.info("出口业务-出运明细-新增、修改 req=" + req.toString());
            UserEntity user = (UserEntity) this.getBean("user");
            String name = user.getName();
            String code = user.getCode();
            return carryDetailService.add(req, name, code);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-新增、修改异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 详情
     *
     * @param id 详情id
     * @return 详情信息
     */
    @GetMapping("/detail")
    @ResponseBody
    public R detail(Integer id) {
        try {
            LOGGER.info("出口业务-出运明细-详情：id=" + id);
            CarryDetailVo detailVo = carryDetailService.detail(id);
            return R.build(detailVo);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-详情异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 获取本月出运单据
     *
     * @return 本月出运单据
     */
    @GetMapping("/statistics/getCarryBillNoCount")
    @ResponseBody
    public R getCarryBillNoCount() {
        try {
            LOGGER.info("出口业务-出运明细-获取本月出运单据信息");
            UserEntity user = (UserEntity) this.getBean("user");
            String name = user.getName();
            String code = user.getCode();
            long count = carryDetailService.getCarryBillNoCount(name, code);
            return R.build(count);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-获取本月出运单据异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 获取本月外销、出货统计
     *
     * @return 本月外销、出货统计
     */
    @GetMapping("/statistics/statisticsChartInfo")
    @ResponseBody
    public R statisticsChartInfo() {
        try {
            LOGGER.info("出口业务-出运明细-获取本月外销、出货统计信息");
            Object object = carryDetailService.statisticsChartInfo();
            return R.build(object);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-获取本月外销、出货统计异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    /**
     * 采购产品情况一览统计
     *
     * @return 采购产品情况一览统计
     */
    @GetMapping(value = "statistics/getPurchaseStatisticsOneByPage")
    @ResponseBody
    public R getPurchaseStatisticsOneByPage(PurchaseStatisticsOneReq req) {
        try {
            LOGGER.info("出口业务-出运明细-采购产品情况一览统计");
            PageInfo<StatisticsPurchaseInfoVo> pageInfo = carryDetailService.getPurchaseStatisticsOneByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-采购产品情况一览统计异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 获取采购产品情况一览统计并导出
     *
     * @return 获取采购产品情况一览统计并导出
     */
    @GetMapping(value = "statistics/export/purchase")
    @ResponseBody
    public R getPurchaseStatisticsAndExport(PurchaseStatisticsOneReq req) {
        try {
            LOGGER.info("出口业务-出运明细-获取采购产品情况一览统计并导出-导出Excel");
            JSONObject obj = carryDetailService.getPurchaseStatisticsAndExport(req);
            return R.build(obj);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-获取采购产品情况一览统计并导出-导出Excel异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 按出运明细统计采购付款信息
     *
     * @return 按出运明细统计采购付款信息
     */
    @GetMapping(value = "statistics/getStatisticsCarryDetailPaymentByPage")
    @ResponseBody
    public R getStatisticsCarryDetailPaymentByPage(CarryDetailStatisticsPaymentReq req) {
        try {
            LOGGER.info("出口业务-出运明细-按出运明细统计采购付款信息");
            PageInfo<StatisticsCarryDetailPaymentVo> pageInfo = carryDetailService.getStatisticsCarryDetailPaymentByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-按出运明细统计采购付款信息异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 按出运明细统计采购付款信息-导出
     *
     * @return 按出运明细统计采购付款信息
     */
    @GetMapping(value = "export/getStatisticsCarryDetailPaymentExport")
    @ResponseBody
    public R getStatisticsCarryDetailPaymentExport(CarryDetailStatisticsPaymentReq req) {
        try {
            LOGGER.info("出口业务-出运明细-按出运明细统计采购付款信息-导出");
            JSONObject obj = carryDetailService.getStatisticsCarryDetailPaymentExport(req);
            return R.build(obj);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-按出运明细统计采购付款信息-导出异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 供应商出货详情统计
     *
     * @return 供应商出货详情统计--分页
     */
    @GetMapping(value = "statistics/getShippingDetailByPage")
    @ResponseBody
    public R getShippingDetailByPage(statisticShippingDetailReq req) {
        try {
            LOGGER.info("出口业务-出运明细-供应商出货详情统计");
            PageInfo<StatisticShippingDetailRsp> pageInfo = carryDetailService.getShippingDetailByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-供应商出货详情统计异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 供应商出货详情统计--导出
     * @return
     */
    @GetMapping(value = "export/getShippingDetailByPageExport")
    @ResponseBody
    public R getShippingDetailByPageExport(statisticShippingDetailReq req) {
        try {
            LOGGER.info("出口业务-出运明细-供应商出货详情统计-导出");
            JSONObject obj = carryDetailService.getShippingDetailByPageExport(req);
            return R.build(obj);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-供应商出货详情统计导出异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }



    /**
     * 采购排产及计划统计
     *
     * @return 采购排产及计划统计
     */
    @GetMapping(value = "statistics/purchaseStatisticsTwoByPage")
    @ResponseBody
    public R purchaseStatisticsTwoByPage(PurchaseStatisticsTwoReq req) {
        try {
            LOGGER.info("出口业务-出运明细-采购排产及计划统计");
            PageInfo<PurchaseStatisticsTwoRes> pageInfo = carryDetailService.getStatisticsTwoPurchaseInfo(req);
            List<PurchaseStatisticsTwoRes> infoList = pageInfo.getList();
            Map<String, List<PurchaseStatisticsTwoRes>> listMap = infoList.stream().
                    filter(p -> StringUtils.isNotEmpty(p.getPurchaseNo())).
                    collect(Collectors.groupingBy(p -> p.getPurchaseNo()));

            return R.build(0, "", pageInfo.getTotal(), infoList,listMap.size());
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-采购排产及计划统计异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 采购排产及计划统计-导出
     *
     * @return 采购排产及计划统计
     */
    @GetMapping(value = "export/purchaseStatisticsTwoExport")
    @ResponseBody
    public R purchaseStatisticsTwoExport(PurchaseStatisticsTwoReq req) {
        try {
            LOGGER.info("出口业务-出运明细-采购排产及计划统计");
            JSONObject obj = carryDetailService.getStatisticsTwoPurchaseInfoExport(req);
            return R.build(obj);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-采购排产及计划统计异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    /**
     * 校验数据是否被调用
     * @param shipmentDetailNo 出运明细号
     * @return 0:未调用 1:报关调用 2:结汇调用 3:付款调用
     */
    @GetMapping("/checkDataIsUsed")
    @ResponseBody
    public R checkDataIsUsed(String shipmentDetailNo){
        try {
            LOGGER.info("出口业务-出运明细修改-校验数据是否被调用 shipmentDetailNo="+shipmentDetailNo);
            int result = carryDetailService.checkDataIsUsed(shipmentDetailNo);
            return R.build(result);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细修改-校验数据是否被调用异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 校验产品数据是否被调用
     *
     * @param productCode 产品编码
     * @param specNo      规格编码
     * @return 0:未调用 1:外销调用 2:备货调用 3:采购调用 4:库存调用
     */
    @GetMapping("/checkProductIsUsed")
    @ResponseBody
    public R checkProductIsUsed(String productCode, String specNo) {
        try {
            LOGGER.info("出口业务-出运明细-产品模块产品修改-校验数据是否被调用 productCode=" + productCode + ",specNo" + specNo);
            int result = carryDetailService.checkProductIsUsed(productCode, specNo);
            return R.build(result);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-产品模块产品修改-校验数据是否被调用异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 已做明细未结汇
     *
     * @return 已做明细未结汇--分页
     */
    @GetMapping(value = "statistics/getDetailUnBillExchangeByPage")
    @ResponseBody
    public R detailUnBillExchangeByPage(DetailUnBillExchangeReq req) {
        try {
            LOGGER.info("出口业务-出运明细-已做明细未结汇");
            PageInfo<DetailUnBillExchangeRsq> pageInfo = carryDetailService.detailUnBillExchangeByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-已做明细未结汇统计异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 已做明细未结汇
     *
     * @return 已做明细未结汇-导出
     */
    @GetMapping(value = "export/getDetailUnBillExchangeExport")
    @ResponseBody
    public R detailUnBillExchangeExport(DetailUnBillExchangeReq req) {
        try {
            LOGGER.info("出口业务-出运明细-已做明细未结汇-导出");
            JSONObject obj = carryDetailService.detailUnBillExchangeExport(req);
            return R.build(obj);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-已做明细未结汇统计-导出异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    /**
     * 已出运未结汇（物流）--分页
     */
    @GetMapping(value = "statistics/detailShippedUnExchangeByPage")
    @ResponseBody
    public R detailShippedUnExchangeByPage(DetailShippedUnExchangeReq req) {
        try {
            LOGGER.info("出口业务-出运明细-已出运未结汇（物流）req="+req);
            PageInfo<DetailShippedUnExchangeRsp> pageInfo = carryDetailService.detailShippedUnExchangeByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-已做明细未结汇 统计异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
    /**
     * 已出运未结汇（物流）-导出
     */
    @GetMapping(value = "export/detailShippedUnExchangeExport")
    @ResponseBody
    public R detailShippedUnExchangeExport(DetailShippedUnExchangeReq req) {
        try {
            LOGGER.info("出口业务-出运明细-已出运未结汇（物流）-导出req="+req);
            JSONObject obj = carryDetailService.detailShippedUnExchangeExport(req);
            return R.build(obj);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-已出运未结汇（物流）-导出异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    /**
     * 出运是否结汇统计
     * @param req 查询参数实体
     * @return 出运是否结汇统计
     */
    @GetMapping("/statistics/getShipmentIsBillExchangeByPage")
    @ResponseBody
    public R getShipmentIsBillExchangeByPage(ShipmentIsBillExchangeReq req) {
        try {
            LOGGER.info("出口业务-出运明细-出运是否结汇统计: req=" + req.toString());
            PageInfo<ShipmentIsBillExchangeVo> pageInfo = carryDetailService.getShipmentIsBillExchangeByPage(req);
            return R.build(0, "", pageInfo.getTotal(), pageInfo.getList());
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-出运是否结汇统计异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }

    /**
     * 出运明细产品、配件终止、取消终止
     * @param req 操作入参
     * @return 操作状态
     */
    @PostMapping(value = "updateProductOrPartsStatus")
    @ResponseBody
    public R updateProductOrPartsStatus(@RequestBody UpdateProductOrPartsStatusReq req) {
        try {
            LOGGER.info("出口业务-出运明细-更新产品或配件状态 req=" + req.toString());
            return carryDetailService.updateProductOrPartsStatus(req);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-更新产品或配件状态异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }


    /**
     * 根据 外销合同号 产品编码 查询该产品的剩余数量
     * @param shipmentNo 出运计划编码
     * @param shipmentPlanProductId 出运计划产品的id
     * @param exportCode 外销合同号
     * @param productCode 产品编码
     * @param specNo 规格编码
     * @return 剩余数量
     */
    @RequestMapping("getSurplusAmount")
    @ResponseBody
    public R getSurplusAmount(String shipmentNo,Integer shipmentPlanProductId,String exportCode,String productCode,String specNo){
        try {
            LOGGER.info("出口业务-出运明细-查询该产品的剩余数量");
            Integer num=carryDetailService.surplusAmount(shipmentNo, shipmentPlanProductId, exportCode, productCode, specNo);
            return R.build(num);
        } catch (Exception e) {
            LOGGER.info("出口业务-出运明细-查询该产品的剩余数量异常:" + e);
            return R.buildError(ResultStatusEnum.SYSTEM_ERROR);
        }
    }
}
